package com.jia.leetcode2.string;

import java.io.InputStream;

/**
 * @program: designPattern
 * @description:  字符转换成整数
 * @author: STU756
 * @create: 2021-03-25 14:46
 */
public class String2Integer {

    private static final int MAXDIV10 = Integer.MAX_VALUE / 10;

    public int atoi(String s) {
        int i = 0, n = s.length();
        //去除空格
        while(i < n && s.charAt(i) == ' ') { i++; }
        int sign = 1;
        if(i < n && s.charAt(i) == '-') {
            sign = -1;
            ++i;
        }else if(i < n && s.charAt(i) == '+') {
            ++i;
        }
        int num = 0;
        while(i < n && Character.isDigit(s.charAt(i))) {
            int digit = Character.getNumericValue(s.charAt(i));
            if(num > MAXDIV10 || num == MAXDIV10 && digit >= 8) {
                return sign == 1? Integer.MAX_VALUE : Integer.MIN_VALUE;
            }
            num = num * 10 + digit;
        }
        //去除空格
        while(i < n && s.charAt(i) == ' ') { i++; }
        return sign * num;
    }
}
